package danran.rpc.client.loadbalance;

import danran.rpc.client.discovery.ServiceDiscovery;
import danran.rpc.common.service.CacheItem;
import danran.rpc.common.service.Service;

import java.net.ServerSocket;
import java.util.List;
import java.util.Map;

/**
 * @Classname ServiceGetter
 * @Description TODO
 * @Date 2021/9/29 16:44
 * @Created by ASUS
 */
public class ServiceGetter {

    private Map<String, CacheItem> cacheList;

    private ServiceDiscovery serviceDiscovery;

    public ServiceGetter(Map<String, CacheItem> cacheList, ServiceDiscovery serviceDiscovery) {
        this.cacheList = cacheList;
        this.serviceDiscovery = serviceDiscovery;
    }

    public Service get(String serviceName) {
        CacheItem cacheItem = cacheList.getOrDefault(serviceName, null);
        if (cacheItem == null) {
            List<Service> services = serviceDiscovery.getServices(serviceName);
            cacheItem = new CacheItem(services);
            cacheList.put(serviceName, cacheItem);
        }

        return selectService(cacheItem);
    }

    private Service selectService(CacheItem cacheItem) {
        if (cacheItem.getServiceList().size() == 0) {
            throw new RuntimeException("No such service instance available!");
        }
        double t_w = -1.0;
        int minIndex = 0;
        List<Double> w = cacheItem.getW();
        for (int i = 0; i < w.size(); i++) {
            if (t_w > w.get(i)) {
                t_w = w.get(i);
                minIndex = i;
            }
        }
        return cacheItem.getServiceList().get(minIndex);
    }

}
